# -*- coding: utf-8-*-
from openerp.osv import osv, fields
try:
    from cStringIO import StringIO
except:
    from StringIO import StringIO
import base64
import simplejson


class create_country(osv.osv_memory):
    _name = 'create.country'

    _columns = {
        'raw_city_file': fields.binary(u'地理位置'),
        'filename': fields.char(u'文件名称'),
    }

    def _get_description(self, cr, uid, context=None):
        state_obj = self.pool.get('res.country.state')

        import sys
        reload(sys)
        sys.setdefaultencoding('utf-8')

        state_ids = state_obj.search(cr, uid, [('country_id.name', '=', u'中国')], context=context)

        res = []
        for state in state_obj.browse(cr, uid, state_ids, context=context):
            res.append({'name': state.name, 'value': 'state-' + str(state.id)})

            for city in state.city_ids:
                res.append({'name': city.city_name, 'value': 'city-' + str(city.id), 'parent': 'state-' + str(state.id)})

                for county in city.country_ids:
                    res.append({'name': county.county_name, 'value': 'county-' + str(county.id), 'parent': 'city-' + str(city.id)})

        temp_file = StringIO(simplejson.dumps(res))

        temp_file.flush()
        temp_file.seek(0)

        return base64.encodestring(temp_file.getvalue())

    _defaults = {
        'raw_city_file': _get_description,
        'filename': 'list.json',
    }
